import { useQuery } from 'vue-query';

const GET = 'GET';
export const useGet = (key, url, options = {}, extraQuery = {}) => {
	const { method = GET, query = null, format = null } = options;

	const feather = async () => {
		const params = { ...(extraQuery?.value || {}) };
		const queryString = new URLSearchParams(params).toString();
		try {
			const response = await fetch(`${url}?${queryString}`, {
				method,
				headers: { 'Content-Type': 'application/json;charset=utf-8' },
				...(method === GET ? {} : { body: JSON.stringify(params) }),
			});
			if (!response.ok) {
				throw new Error(`请求失败，状态码： ${response.statusText}`);
			}
			const data = await response.json();
			return format && typeof format === 'function' ? format(data) : data;
		} catch (e) {
			throw new Error(`错误信息：${e}`);
		}
	};

	return useQuery({
		queryKey: [...key, extraQuery],
		queryFn: () => feather(),
	});
};
